require(['grid', 'topBar', 'layout', 'date'], function () {
	var $gridList = $('#grid'),
    	$top = $('#top');
	var speedAnalysisDialog, manySpeedAnalysisDialog;
	$('body').layout();
	$top.topBar({
        left: [{
            type: 'filter-more',
            dateType: 'custom',
            search: function () {
            	
                if (getPostData()) {
                	if(postData.addDrv!="1"){
                		$gridList.grid('hideCol',"drvName");
                	}else{
                		$gridList.grid('showCol',"drvName");
                	}
                    $gridList.grid('setGridParam', {
                        datatype: "json",
                        postData: postData
                    }).trigger("reloadGrid");
                }
            },
            item: [
                {
                    text: '时间快捷',
                    name1: 'beginTime',
                    name2: 'endTime',
                    type: 'dateLine'
                }, {
                    text: '分析对象',
                    name: 'addDrv',
                    type: 'item-select',
                    data: [
                        {text: '车辆', value: ''},
                        {text: '驾驶员', value: '1'}
                    ]
                }
            ]
        }],
        right: [
            {
                text: '导出',
                type: 'export-btn',
                authority: '',
                item: [
                    {
                        text: 'Excel导出',
                        click: function () {
                            exportFile('Excel');
                        }
                    },
                    {
                        text: 'PDF导出',
                        click: function () {
                            exportFile('Pdf');
                        }
                    }
                ]
            },
            {
				text: '对比分析',
				type: 'btn',
				click: function () {
					analysisData();
				}
			}
        ]
    });
	
	
	$gridList.grid({
		url :"/speedAnalysis/searchSpeedAnalysis.htm",
		shrinkToFit:false,
//		cmTemplate: {
//			sortable: false,
//		},
//		sortname :"TO_NUMBER(ENER_RANK),FUEL_TYPE_CODE",
		colModel : [ {name : "id", label: "id", key: true, hidden: true},
		             {name : "fuelTypeCode", label: "fuelTypeCode", key: true, hidden: true},
		    {name : "drvName",label : "驾驶员",width:"70",sorttype : "text",align : "left"},
			{name : "licPltNo",label : "车牌号",width:"70",sorttype : "text",align : "left",
				cellattr: function(rowId, tv, rawObject, cm, rdata) {
                    return 'id=\'licPltNo' + rowId + "\'";
                }},
			{name : "carInCd",label : "车辆编号",width:"75",sorttype : "text",align : "left",
				cellattr: function(rowId, tv, rawObject, cm, rdata) {
                    return 'id=\'carInCd' + rowId + "\'";
                }},
			{name : "lineName",label : "营运线路",width:"75",sorttype : "text",align : "left",
				cellattr: function(rowId, tv, rawObject, cm, rdata) {
                    return 'id=\'lineName' + rowId + "\'";
                }},
			{name : "organName",label : "所属机构",width:"75",sorttype : "text",align : "left",
				cellattr: function(rowId, tv, rawObject, cm, rdata) {
                    return 'id=\'organName' + rowId + "\'";
                }},
			{name : "rcrdTime",label : "运营日期",width:"115",align : "right",
				cellattr: function(rowId, tv, rawObject, cm, rdata) {
                    return 'id=\'rcrdTime' + rowId + "\'";
                }},
			{name : "totRngOprtDura",label : "运行时长",width:"75",align : "right",
				cellattr: function(rowId, tv, rawObject, cm, rdata) {
                    return 'id=\'totRngOprtDura' + rowId + "\'";
                }},
			{name : "totRngMile",label : "运行里程",width:"75",align : "right",formatter:"currency",
				cellattr: function(rowId, tv, rawObject, cm, rdata) {
                    return 'id=\'totRngMile' + rowId + "\'";
                }},
			
			{name : "fuelTypeName",label : "燃料类型",sortable:false,align : "center",width:80},
			{name : "totRngEnerCons",label : "运行能耗",width:"75",align : "right",formatter:"currency"},
			{name : "enerConsMile",label : "百公里能耗(L|m³|KWh/100KM)",width:"155",align : "right",formatter:"currency"},
			
			    {name : "enerRank",label : "能耗排名",width:"75",align : "right",
			    	cellattr: function(rowId, tv, rawObject, cm, rdata) {
                    return 'id=\'enerRank' + rowId + "\'";
                }},
			    
			{name : "idliDuraStr",label : "怠速时长",width:"75",align : "right" },
			{name : "idliDuraRate",label : "怠速时长百分比",width:"120",align : "right" },
			{name : "airCondiIdliDuraStr",label : "空调怠速时长",width:"120",align : "right" },
			{name : "airCondiIdliDuraRate",label : "空调怠速时长百分比",width:"130",align : "right" },
			{name : "slowSpdRevoDuraStr",label : "低转时长",width:"75",align : "right" },
			{name : "slowSpdRevoDuraRate",label : "低转时长百分比",width:"115",align : "right" },
			{name : "lowEnerAreaDriveDuraStr",label : "绿区时长",width:"75",align : "right"},
			{name : "lowEnerAreaDriveDuraRate",label : "绿区时长百分比",width:"115",align : "right"},
			{name : "highSpdRevoDuraStr",label : "高转时长",width:"75",align : "right"},
			{name : "highSpdRevoDuraRate",label : "高转时长百分比",width:"115",align : "right"},
			{name : "suspeedDuraStr",label : "超转时长",width:"75",align : "right"},
			{name : "suspeedDuraRate",label : "超转时长百分百",width:"115",align : "right"},
			{name : "mostEcnRtteSpdDuraStr",label : "最经济转速时长",width:"115",align : "right"},
			{name : "mostEcnRtteSpdDuraRate",label : "最经济转速时长百分比",width:"155",align : "right"},
			{name : "revDuraStr",label : "反转时长",width:"75",align : "right"},
			{name : "revDuraRate",label : "反转时长百分比",width:"115",align : "right"},
			{name : "speedOperate", label: "图表分析",width:"105",align: "center",formatter: 'operArea',
				formatoptions: [{
                    text: '图表分析',
                    css:'operate-edit',
                    click: function (data) {
                    	getAnalysisDialog('图表分析').dialog('exec', 'showCharts',data.lineId, data.organId, data.rcrdTime, data.idliDuraRate, data.airCondiIdliDuraRate,
                    		data.slowSpdRevoDuraRate, data.lowEnerAreaDriveDuraRate, data.highSpdRevoDuraRate, data.suspeedDuraRate, data.mostEcnRtteSpdDuraRate, 
                    		data.revDuraRate, data.licPltNo,data.drvName,data.lineName,data.organName,data.fuelTypeCode,$('#top').parent().getValues().beginTime, 
                    		$('#top').parent().getValues().endTime);
                    }
                }]
			},
			{name : "lineId",index : "lineId",hidden: true},
			{name : "organId",index : "organId",hidden: true}],
		showPaper : true,
		onCellSelect:function(id){
			$gridList.find("#"+id+" input[type=radio]").click();
		},
		gridComplete: function() {
            var gridName = "grid";
            Merger(gridName, 'licPltNo');
            Merger(gridName, 'carInCd');
            Merger(gridName, 'lineName');
            Merger(gridName, 'organName');
            Merger(gridName, 'rcrdTime');
            Merger(gridName, 'totRngOprtDura');
            Merger(gridName, 'totRngMile');
            Merger(gridName, 'enerRank');
            //Merger(gridName, 'carOperate');
        }
	});
	
	
	function exportFile(suffix) {
        if ($gridList.getGridParam("reccount") > 0 && getPostData()) {
            var url = "/speedAnalysis/exportSpeedAnalysis" + suffix + ".htm";
            $.exportFile(url, postData);
        } else {
            $.messager.alert("警告", "请先查询数据！", "info");
        }
    }
	
	//获取需要传递到后台的参数
    function getPostData() {
        postData = null;
        var type = 'LINE';
        var lineIds = commonFun.getLeftTreeCheckedNodes(type);
        if (lineIds == null || !lineIds.length) {
            $.messager.alert("提示", "请先选择左侧树的线路!", "warning");
            return false;
        }
        postData = $('#top').parent().getValues();
        postData.type = type;
        postData.orgIds = lineIds.toString();
        return true;
    }
	
	function getAnalysisDialog(option) {
//    	funName = flag;
        option = option || {};
        if (speedAnalysisDialog) {
        	speedAnalysisDialog.dialog('open');
            if (option.title) {
            	speedAnalysisDialog.dialog('setOption', 'title', option.title);
            }
        } else {
        	speedAnalysisDialog = $('<div>').dialog({
                title: option.title || '图表分析',
                url: './energy/report/speedAnalysisDialog.htm',
                height: 400,
                width: 1040,
                autoOpen: true,
                buttons: [
                    {
                        text: '关闭',
                        css: 'btn-cancel',
                        click: function () {
                        	$(this).dialog('close');
                        }
                    }
                ]
            });
        }
        return speedAnalysisDialog;
    }
	
	
	function getCompareAnalysisDialog(option) {
//    	funName = flag;
        option = option || {};
        if (manySpeedAnalysisDialog) {
        	manySpeedAnalysisDialog.dialog('open');
            if (option.title) {
            	manySpeedAnalysisDialog.dialog('setOption', 'title', option.title);
            }
        } else {
        	manySpeedAnalysisDialog = $('<div>').dialog({
                title: option.title || '图表分析',
                url: './energy/report/manySpeedAnalysisDialog.htm',
                height: 550,
                width: 720,
                autoOpen: true,
                buttons: [
                    {
                        text: '关闭',
                        css: 'btn-cancel',
                        click: function () {
                        	$(this).dialog('close');
                        }
                    }
                ]
            });
        }
        return manySpeedAnalysisDialog;
    }
	
	
	function analysisData(){
		var rowIds = $gridList.grid("getGridParam", "selarrrow");
		if (rowIds.length == 0  ) {
			$.messager.alert("提示","请至少选择一个");
			return false;
		}
		var getResult = $gridList.getRowData(rowIds[0]);
		var rowDatas = [];
		for(var i=0;i < rowIds.length; i++){
			rowDatas.push($gridList.getRowData(rowIds[i]));
		}
		
		getCompareAnalysisDialog("对比分析").dialog("exec", "showCharts", getResult.lineId, getResult.organId, getResult.rcrdTime, 
				getResult.fuelTypeCode, rowDatas, $('#top').parent().getValues().beginTime, $('#top').parent().getValues().endTime);
	}
	
	
	//公共调用方法
	function Merger(gridName, CellName) {
		//得到显示到界面的id集合
	    var mya = $("#" + gridName + "").getDataIDs();
	    //当前显示多少条
	    var length = mya.length;
	    for (var i = 0; i < length; i++) {
	        //从上到下获取一条信息
	        var before = $("#" + gridName + "").jqGrid('getRowData', mya[i]);
	        //定义合并行数
	        var rowSpanTaxCount = 1;
	        for (var j = i + 1; j <= length; j++) {
	            //和上边的信息对比 如果值一样就合并行数+1 然后设置rowspan 让当前单元格隐藏
	            var end = $("#" + gridName + "").jqGrid('getRowData', mya[j]);
	            //if(CellName=='carOperate' && before['licPltNo'] == end['licPltNo']){
	            //	rowSpanTaxCount++;
	            //    $("#" + gridName + "").setCell(mya[j], CellName, '', { display: 'none' });
	            //}else 
	            if (before[CellName] == end[CellName] && before['rcrdTime'] == end['rcrdTime']) {
	                rowSpanTaxCount++;
	                $("#" + gridName + "").setCell(mya[j], CellName, '', { display: 'none' });
	            } else {
	                rowSpanTaxCount = 1;
	                break;
	            }
	            $("#" + CellName + "" + mya[i] + "").attr("rowspan", rowSpanTaxCount);
	        }
	    } 
	}
	
});